package com.shinhye.elephantsafe;

import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.shinhye.elephantsafe.db.dao.BlackListDao;
import com.shinhye.elephantsafe.domain.BlackNumber;

public class TelephonySafeActivity extends Activity {
	private int total; //黑名单记录总数
	private ListView lv_blacklist;
	private List<BlackNumber> list;
	private BlackListDao dao;
	private LinearLayout ll_loading;
	private int start = 0;
	private MyAdapter adapter;
	private boolean isLoading = false;
	private TextView tv_no_blackphone;
	
	private Handler handler = new Handler(){

		@Override
		public void handleMessage(android.os.Message msg) {
			ll_loading.setVisibility(View.INVISIBLE);
			if(list.size() == 0)
				tv_no_blackphone.setVisibility(View.VISIBLE);
			else
				tv_no_blackphone.setVisibility(View.INVISIBLE);
			
			if(adapter == null) {
				adapter = new MyAdapter();
				lv_blacklist.setAdapter(adapter);
			} else {
				adapter.notifyDataSetChanged();
			}
			isLoading = false;
		}
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_telephonysafe);
		
		dao = new BlackListDao(this);
		lv_blacklist = (ListView) findViewById(R.id.lv_blacklist);
		ll_loading = (LinearLayout) findViewById(R.id.ll_loading);
		ll_loading.setVisibility(View.VISIBLE);
		tv_no_blackphone = (TextView) findViewById(R.id.tv_no_blackphone);
		
		getData();
		
		lv_blacklist.setOnScrollListener(new OnScrollListener() {
			// 滚动状态变化:
			// 静止-->滚动
			// 滚动-->静止
			// 手指触摸滚动-->惯性滑动
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				switch(scrollState) {
				case OnScrollListener.SCROLL_STATE_IDLE:
					int position = lv_blacklist.getLastVisiblePosition();
					int length = list.size();
					total = dao.getCount();
					if(isLoading) {
						return;
					}
					if(position >= length - 3) {
						start += 20;
						if(start >= total) {
							Toast.makeText(TelephonySafeActivity.this, "已经到达末尾了！", Toast.LENGTH_SHORT).show();
							return;
						}
						Toast.makeText(TelephonySafeActivity.this, "正在加载中，请稍候...", Toast.LENGTH_SHORT).show();
						getData();
					}
					break;
				case OnScrollListener.SCROLL_STATE_FLING:
					break;
				case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
					break;
				}
			}
			@Override
			//滚动时
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
			}
		});
	}
	
	private void getData() {
		isLoading = true;
		new Thread(new Runnable() {
			@Override
			public void run() {
				
				if(list == null)
					list = dao.findPart(String.valueOf(start));
				else
					list.addAll(dao.findPart(String.valueOf(start)));
				handler.sendEmptyMessage(0);
			}
		}).start();
	}
	
	class MyAdapter extends BaseAdapter {
		private final String TAG = "MyAdapter";
		@Override
		public int getCount() {
			return list.size();
		}
		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			View view;
			ViewHolder holder;
			if(convertView != null) {
				Log.i(TAG, "历史存储的view" + position);
				view = convertView;
				holder = (ViewHolder) view.getTag();
			} else {
				Log.i(TAG, "新创建的view" + position);
				view = View.inflate(TelephonySafeActivity.this, R.layout.item_blacklist, null);
				/* 寻找孩子的过程 是一个比较耗时 消耗资源的操作 进一步的优化。
				       没有必要每一次都去查看每个孩子的特征 根据id得到孩子的引用。
				       只需要在孩子出生的时候 ， 找到特征 ，把特征给存起来 */
				holder = new ViewHolder();  // 买了一个记事本 记录孩子的信息。
				holder.tv_number = (TextView) view.findViewById(R.id.tv_number);
				holder.tv_mode = (TextView) view.findViewById(R.id.tv_mode);
				holder.iv_trash = (ImageView) view.findViewById(R.id.iv_trash);
				view.setTag(holder);
			}
			holder.tv_number.setText(list.get(position).getNumber());
			int mode = list.get(position).getMode();
			switch(mode) {
			case 0:
				holder.tv_mode.setText("电话拦截");
				break;
			case 1:
				holder.tv_mode.setText("短信拦截");
				break;
			case 2:
				holder.tv_mode.setText("电话+短信拦截");
				break;
			}
			holder.iv_trash.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Builder builder = new AlertDialog.Builder(TelephonySafeActivity.this);
					builder.setIcon(android.R.drawable.ic_dialog_alert);
					builder.setTitle("删除黑名单");
					builder.setMessage("您确定要删除这条黑名单记录吗？");
					builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dao.delete(list.get(position).getNumber());
							list.remove(position);
							handler.sendEmptyMessage(0);
						}
					});
					builder.setNegativeButton("取消", null);
					builder.show();
				}
			});
			
			return view;
		}
		
		@Override
		public Object getItem(int position) {
			return null;
		}
		@Override
		public long getItemId(int position) {
			return 0;
		}
	}
	
	//定义成静态类后，new对象时内存中有字节码则直接使用，而不用重复加载字节码
	static class ViewHolder {
		TextView tv_number;
		TextView tv_mode;
		ImageView iv_trash;
	}
	
	//添加黑名单
	public void addblacklist(View v) {
		Intent intent = new Intent(this, AddBlackPhoneActivity.class);
		startActivityForResult(intent, 100);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(requestCode == 100) {
			if(resultCode == RESULT_OK) {
				String number = data.getStringExtra("number");
				int mode = data.getIntExtra("mode", 2);
				BlackNumber blackNumber = new BlackNumber();
				blackNumber.setNumber(number);
				blackNumber.setMode(mode);
				
				list.add(0, blackNumber);
				handler.sendEmptyMessage(0);
			}
		}
	}
}
